<template>
  <div class="app-container"   v-loading="pageLoading">
    <div id="steps" class="m-b-10">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="课程基本信息"></el-step>
        <el-step title="课程大纲"></el-step>
        <el-step title="发布课程"></el-step>
      </el-steps>
    </div>
    <div id="uploadForm" v-show="active == 1">
      <el-form
        ref="uploadCourseForm"
        :model="uploadCourseForm"
        label-width="80px"
        status-icon
        :rules="courseRules"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="uploadCourseForm.courseName" placeholder="请不要包含“-“这种字符"></el-input>
        </el-form-item>
        <el-form-item label="课程封面">
          <el-row>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="handleAvatarSuccess"
                :auto-upload="false"
                :on-change="handleChange"
                v-loading="uploadCourseLoading"
                 ref="upload"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
              >
                <el-button slot="trigger" size="small" type="primary"
                  >选取文件</el-button
                >
                <el-button
                  style="margin-left: 10px"
                  size="small"
                  type="success"
                  @click="submitUploadCoverImage"
                  >上传到服务器</el-button
                >
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-col>
            <el-col :span="12" v-show="src!=null">
              <el-image
                style="width: 200px; height: 100px"
                :src="src"
                v-show="showCoverImae"
              >
              <div slot="placeholder" class="image-slot">
        加载中<span class="dot">图片加载中...</span>
      </div>
              </el-image>
            </el-col>
          </el-row>
        </el-form-item>
        <div >
          <el-form-item label="课程类型" prop="courseTypeIdList">
            <el-select
              v-model="uploadCourseForm.courseTypeIdList"
              multiple
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option-group
                v-for="(group,index) in courseOptions"
                :key="index"
                :label="group.label"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.courseTypeId"
                  :label="item.typeName"
                  :value="item.courseTypeId"
                >
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item label="课程学分" prop="credit">
            <el-input-number
              v-model="uploadCourseForm.credit"
              :step="2"
              type="number"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="课程码">
            <el-row>
              <el-col :span="6">
                <el-switch
                  v-model="isNeedReciver"
                  active-text="需要邀请码"
                  inactive-text="不需要邀请码"
                >
                </el-switch>
              </el-col>
              <el-col :span="6">
                <el-switch
                  v-model="open"
                  active-text="公开"
                  inactive-text="不公开"
                >
                </el-switch>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12"
                ><el-input
                  v-model="uploadCourseForm.reciverUrls"
                  v-show="isNeedReciver"
                  :disabled="true"
                ></el-input
              ></el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="教师信息">
            <el-cascader
            style="width:auto;"
            clearable
            filterable
              v-model="teacherValue"
              :options="departMentOptions"
              :props="{ expandTrigger: 'hover' }"
              @change="handleCascaderChange"></el-cascader>
          </el-form-item>
        </div>
        <el-form-item label="课程描述">
          <el-input
            type="textarea"
            v-model="uploadCourseForm.descriptions"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addCourse('uploadCourseForm')">{{
            uploadButtonText
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="step2" v-show="active == 2" v-loading="step2loading">
      <div id="step2-dialog">
        <el-dialog title="新建章节" :visible.sync="dialog_newChapter">
          <el-form :model="dynamicValidateForm"  label-width="100px" class="demo-dynamic">
            <el-form-item label="章节名称" :label-width="formLabelWidth">
             <el-row>
               <el-col :span="18"
                  >
                  <el-input
                v-model="dynamicValidateForm.courseName"
                autocomplete="off"
              ></el-input>
                  </el-col>
                     <el-col :span="6"
                  >
                  <el-button type="warning" icon="el-icon-plus" circle @click="addDomain"></el-button>
                  </el-col>
               </el-row>

            </el-form-item>

            <el-form-item
              v-for="(domain, index) in dynamicValidateForm.domains"
              :label="'子章节名称' + index"
              :key="domain.key"
            >
              <el-row>
               <el-col :span="18"
                  >
                  <el-input v-model="domain.value"></el-input
              ></el-input>
                  </el-col>
                     <el-col :span="6"
                  >
                  <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click.prevent="removeDomain(domain)"
              ></el-button>

                  </el-col>
               </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addChapter()">提交</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div>
        <el-button type="primary" class="m-b-10" @click="dialog_newChapter = true">
          新建章节<i class="el-icon-upload el-icon--right"></i
        ></el-button>
      </div>
      <div style="width: 95%;" class="m-0">
        <el-collapse @change="handleCollapseChange">
          <el-collapse-item
            v-for="item in chapterList"
            :title="item.courseInfo.courseName"
            :name="item.courseInfo.courseId"
            :key="item.courseInfo.courseId"
          >
            <template slot="title" style="position: relative">
              <span>{{item.courseInfo.courseName}}</span>
              <el-button
                type="primary" size="mini"
                style="position:absolute; right:300px;"
                @click="editTitle(item)">编辑标题</el-button>
            </template>
            <div  v-for="sonCourse in item.sonCourseInfo"
            :key="sonCourse.courseId">
            <el-card shadow="hover">
               {{sonCourse.courseName}}
                <el-button type="text" class="button" @click="uploadCourseMaterrial(sonCourse.courseId)">上传课程资料</el-button>
            </el-card>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-dialog title="编辑章节标题" :visible.sync="dialog_editChapter">
          <el-form :model="editForm"  label-width="100px" class="demo-dynamic">
            <el-form-item label="章节名称" :label-width="formLabelWidth">
              <el-row>
                <el-col :span="18">
                  <el-input
                    v-model="editForm.courseName"
                    autocomplete="off"></el-input>
                </el-col>
                <el-col :span="6">
                  <el-button type="warning" icon="el-icon-plus" circle @click="editaddDomain"></el-button>
                </el-col>
              </el-row>

            </el-form-item>

            <el-form-item
              v-for="(domain, index) in editForm.domains"
              :label="'子章节名称' + index"
              :key="domain.key"
            >
              <el-row>
                <el-col :span="18"
                >
                  <el-input v-model="domain.value"></el-input>
                </el-col>
                <el-col :span="6"
                >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click.prevent="editremoveDomain(domain)"
                  ></el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="editChapter()">提交编辑</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <div id='btn' class="f-r m-t-10">
            <el-button-group>
            <el-button type="primary" icon="el-icon-arrow-left" @click="active = 1">上一步</el-button>
            <el-button type="primary" @click="stepTo3">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
      </el-button-group>
        </div>
      </div>
    </div>
    <div v-show="active==3">
    <el-row :gutter="12">
  <el-col :span="12">
    <el-card shadow="always">
     <el-image :src="courseInfo.coverImage"></el-image>
    </el-card>
  </el-col>
  <el-col :span="12">
    <el-card shadow="hover">
      <h1>{{courseInfo.courseName}}</h1>
      <h3><span class="f-14">教师：</span>{{courseInfo.teacherName}}</h3>
      <el-tag   v-for="(item,index) in courseInfo.couseTypeNames"
      :key="index" :type="tagType[index%5]">{{item}}</el-tag>
      <h3 class="f-c-red">学分：{{courseInfo.credit}}</h3>
        <el-card shadow="always">
        <el-tag type="info">描述：</el-tag>
      {{courseInfo.descriptions}}
    </el-card>

    </el-card>
  </el-col>
  <el-button-group class="f-r">
            <el-button plain icon="el-icon-arrow-left" @click="active = 2">上一步</el-button>
            <el-button plain @click="finishCourse">发布课程</el-button>
      </el-button-group>
</el-row>
    </div>
  </div>
</template>

<script>
import DropdownMenu from "@/components/Share/DropdownMenu";
import {
  getCourseType,
  addCourse,
  getCourse,
  deleteCourse,
  addChapter,
  getChapterByCourseId,
  getCourseByCourseId,
  getCompanyInfoWithTeacherList,
  updateChapter,
  deleteChapter,
} from "./uploadCourse.js";
import $ from "jquery";
import moment from "moment";
import { formatTime } from "@/utils/index.js";
import { AddOrSublineDays } from "@/utils/TimeUitls.js";
import {
  isNull,
  warnInfo,
  successInfo,
  errorInfo,
  getHost,
  getCookie,
  getTokenSign,
  getToken,
} from "../../utils/commonUtils.js";
export default {
  name: "Documentation",
  components: { DropdownMenu },
  data() {
    var validateNull = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
      }
    };
    return {
      step2loading:false,
      tokenKey: getTokenSign(), //token标识
      token: getToken(), //token
      pageLoading: false,
      uploadCourseLoading: false,
      //进度条
      active: 1,
      courseIds: [],
      showCoverImae: false,
      src: undefined,
      courseOptions: [],
      isNeedReciver: false,
      open: false,
      uploadButtonText: "下一步",
      courseCoverImageFileList: [],
      coverImage: undefined,
      currentCourseId: undefined,
      /**父级id */
      //课程id
      pid: undefined,
      courseRules: {
        courseName: [{ required: true, message:"课程名称不得为空", trigger: "blur" }],
        courseTypeIdList:[{ required: true, message:"请选择课程类型", trigger: "blur" }],
        credit:[{ required: true, message:"请填写课程学分", trigger: "blur" }],
      },
      /**form */
      //课程信息form
      uploadCourseForm: {},
      //课程章节form
      chapterForm: {},
      /**dialog显示 */
      dialog_newChapter: false,
      dialog_editChapter:false,
      /**collapse */
      //chapter
      activeNames: [],
      /**list */
      chapterList: [],
      materrialList: [],
      formLabelWidth: "120px",
      dynamicValidateForm: {
        domains: [
          {
            value: "",
          },
        ],
        courseName: "",
      },
      /*编辑章节标题的Form表单*/
      editForm:{
        domains: [
          {
            value: "",
            courseId:"",
          },
        ],
        courseName: "",
        courseId:"",
      },
      //课程信息
      courseInfo: {},
      tagType: ["", "success", "info", "warning", "danger"],
      //如果是课程管理员则为true
      courseAdmin: true,
      //课程管理员跳转页面时传递的参数
      admin_courseId: undefined,
      departMentOptions: [],
      teacherValue: [],
    };
  },
  watch: {
    open(val) {
      if (val) {
        this.uploadCourseForm.open = 1;
      } else {
        this.uploadCourseForm.open = 0;
      }
    },
    isNeedReciver(val) {
      if (val) {
        this.uploadCourseForm.isNeedReciver = 1;
        this.uploadCourseForm.reciverUrls = new Date().getTime();
      } else {
        this.uploadCourseForm.isNeedReciver = 0;
        this.uploadCourseForm.reciverUrls = undefined;
      }
    },
    src(val) {
      const _this = this;
      if (isNull(val)) {
        _this.showCoverImae = false;
      } else {
        _this.showCoverImae = true;
      }
    },
  },
  created() {
    //获取正在上传的课程列表
    this.currentCourseId = this.$route.query.courseId;
    if (this.currentCourseId != null) {
      this.active = 2;
      this.getCourse();
    }
    // this.courseAdmin = this.$route.query.courseAdmin;
    // if (isNull(this.courseAdmin)) {
    //   this.courseAdmin = false;
    // }
    // if (this.courseAdmin) {
    //   //获取课程类型列表
    //   this.getCourseType();
    //   //获取讲师信息列表
    //   this.getDepartmentAndTeacherList();
    // }
    //获取课程类型列表
    this.getCourseType();
    //获取讲师信息列表
    this.getDepartmentAndTeacherList();
    this.admin_courseId = this.$route.query.admin_courseId;
    if (!isNull(this.admin_courseId)) {
      this.currentCourseId = this.admin_courseId;
      this.getCourse();
    }
  },
  methods: {
    /*编辑标题*/
    editTitle(item){
      /*父章节赋值*/
      this.editForm.courseName = item.courseInfo.courseName;
      this.editForm.courseId = item.courseInfo.courseId;
      /*子章节赋值*/
      this.editForm.domains=[];
      const _this = this;
      item.sonCourseInfo.forEach(function(son,index){
        var sondata= {
            value: son.courseName,
            courseId:son.courseId,
          };
        _this.editForm.domains.push(sondata);
      })
      /*打开编辑标题对话框*/
      this.dialog_editChapter = true;
    },
    /*提交编辑标题信息：*/
    editChapter(){
      updateChapter(this.editForm).then((response) => {
        this.dialog_editChapter = false;
        this.getChapter();
      })
    },
    //跳转到上传课程资料页面
    uploadCourseMaterrial(courseId) {
      this.$router.push({
        // path: "../uploadCourseMaterrial_Admin/index",
        name:"uploadCourseMaterialAdmin",
        query: {
          courseId: courseId,
        },
      });
    },
    handleCascaderChange(value) {
      if (!isNull(value)) {
        this.uploadCourseForm.teacherIds = value[value.length - 1];
      }
    },
    /**获取部门列表以及对应的讲师信息**/
    getDepartmentAndTeacherList() {
      const _this = this;
      _this.departMentOptions = []; //首先清除信息
      $.ajax({
        url: getHost() + "/identity/company/getCompanyInfoWithTeacherList",
        type: "post",
        //加上这句话,允许浏览器向服务器跨域请求时携带cookie
        xhrFields: {
          withCredentials: true,
        },
        crossDomain: true,
        beforeSend: function (request) {
          request.setRequestHeader(_this.tokenKey, _this.token);
        },
        success: function (response) {
          $(response.data).each(function (index, value) {
            let options = {
              value: undefined,
              label: undefined,
              children: [],
            };
            //第一层信息
            options.value = value.companyId;
            options.label = value.companyName;
            let children = [];
            let childrenOption = {
              value: undefined,
              label: undefined,
            };
            //第二层信息
            $(value.tbUsers).each(function (index, value) {
              childrenOption.value = value.userId;
              childrenOption.label = value.userName;
              children.push(childrenOption);
              options.children = children;
              _this.departMentOptions.push(options);
            });
          });
        },
        error: function (data) {
          errorInfo(_this, "网络连接不畅");
        },
      });
    },
    //发布课程
    finishCourse() {
      const _this = this;
      //课程管理员的话跳转到课程管理页面
      this.$router.push({
        // path: "../courseManagement/courseManagement",
        name:"courseManagement",
      });
    },
    /**
     * 跳到第三步
     * **/
    stepTo3() {
      this.active = 3;
      this.getCourseDetail();
    },
    /**
     * 获取课程详细信息
     * **/
    getCourseDetail() {
      const _this = this;
      var searchForm = {
        courseId: this.pid,
      };
      getCourseByCourseId(searchForm).then((response) => {
        this.courseInfo = response.data;
      });
    },
    /**Domina */
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },
    editremoveDomain(item){
      var index = this.editForm.domains.indexOf(item);
      if (index !== -1) {
        this.editForm.domains.splice(index, 1);
      }
      if(item.courseId!=""){
        deleteChapter(item.courseId).then((response) => {
          this.getChapter();
        })
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: "",
        key: Date.now(),
        courseId:"",
      });
    },
    editaddDomain() {
      this.editForm.domains.push({
        value: "",
        key: Date.now(),
        courseId:"",
      });
    },
    //获取子章节
    getChapter() {
      const _this = this;
      var searchForm = {
        courseId: _this.pid,
      };
      this.step2loading=true;
      $.ajax({
        url: getHost() + "/courseCenter/course/getChapterByCourseId",
        dataType: "json",
        contentType: "application/json",
        type: "post",
        //加上这句话,允许浏览器向服务器跨域请求时携带cookie
        xhrFields: {
          withCredentials: true,
        },
        crossDomain: true,
        beforeSend: function (request) {
          request.setRequestHeader(_this.tokenKey, _this.token);
        },
        data: JSON.stringify(searchForm),
        success: function (response) {
          _this.chapterList = response.data;
           _this.step2loading=false;
        },
        error: function (data) {
          errorInfo(_this, "网络连接不畅");
        },
      });
    },
    //collapse
    handleCollapseChange(val) {},
    //新增章节
    addChapter() {
      const _this = this;
      _this.dynamicValidateForm.pid = _this.pid; //设置父级Id
      addChapter(_this.dynamicValidateForm).then((response) => {
        _this.dialog_newChapter = false;
        _this.dynamicValidateForm = {
          domains: [
            {
              value: "",
            },
          ],
          courseName: "",
        };
        _this.getChapter();
      });
    },
    /**
     *
     * **/
    deleteCourseInfo(courseId) {
      var course = {
        courseId: courseId,
      };
      deleteCourse(course).then((response) => {
        this.courseIds.pop(courseId);
      });
    },
    /**
     * 获取指定id的课程信息
     * **/
    getCourse() {
      const _this = this;
      this.pageLoading = true;
      var course = {
        courseId: this.currentCourseId,
      };
      $.ajax({
        url: getHost() + "/courseCenter/course/getTopCourse",
        dataType: "json",
        contentType: "application/json",
        type: "post",
        //加上这句话,允许浏览器向服务器跨域请求时携带cookie
        xhrFields: {
          withCredentials: true,
        },
        crossDomain: true,
        beforeSend: function (request) {
          request.setRequestHeader(_this.tokenKey, _this.token);
        },
        data: JSON.stringify(course),
        success: function (response) {
          _this.pid = response.data.courseId;
          if (_this.active == 2) {
            _this.getChapter();
          }
          //开始填充表单数据
          _this.uploadCourseForm = response.data;
          //填充教师信息
          _this.teacherValue.push(response.data.departmentId);
          _this.teacherValue.push(response.data.teacherIds);
          _this.src = response.data.coverImage;
          _this.coverImage = response.data.coverImage;
          //回溯邀请码，公开
          if (_this.uploadCourseForm.isNeedReciver == 1) {
            _this.isNeedReciver = true;
          } else {
            _this.isNeedReciver = false;
          }
          if (_this.uploadCourseForm.open == 1) {
            _this.open = true;
          } else {
            _this.open = false;
          }
          _this.pageLoading = false;
        },
        error: function (data) {
          errorInfo(_this, "网络连接不畅");
        },
      });
    },
    /**
     * 新增课程
     * **/
    addCourse(formName) {
      const _this = this;
      this.$refs.uploadCourseForm.validate((valid) =>{
        if(valid){
          this.uploadCourseForm.coverImage = this.coverImage;
          if (!this.open) {
            this.uploadCourseForm.open = 0;
          } else {
            this.uploadCourseForm.open = 1;
          }
          if (!isNull(_this.pid)) {
            this.uploadCourseForm.courseId = _this.pid;
          }
          $.ajax({
            url: getHost() + "/courseCenter/course/addCourse",
            dataType: "json",
            contentType: "application/json",
            type: "post",
            //加上这句话,允许浏览器向服务器跨域请求时携带cookie
            xhrFields: {
              withCredentials: true,
            },
            crossDomain: true,
            beforeSend: function (request) {
              request.setRequestHeader(_this.tokenKey, _this.token);
            },
            data: JSON.stringify(_this.uploadCourseForm),
            success: function (response) {
              //设置课程的id
              _this.pid = response.data.cid;
              _this.active = 2;
              //获取子章节的信息
              _this.getChapter();
            },
            error: function (data) {
              errorInfo(_this, "网络连接不畅");
            },
          });
        }
      })
    },
    /**
     * 获取课程类型
     */
    getCourseType() {
      const _this = this;
      var searchForm = {
        typeName: undefined,
      };
      $.ajax({
        url: getHost() + "/courseCenter/courseType/getCourseType",
        dataType: "json",
        contentType: "application/json",
        type: "post",
        //加上这句话,允许浏览器向服务器跨域请求时携带cookie
        xhrFields: {
          withCredentials: true,
        },
        crossDomain: true,
        beforeSend: function (request) {
          request.setRequestHeader(_this.tokenKey, _this.token);
        },
        data: JSON.stringify(searchForm),
        success: function (response) {
          _this.courseOptions = response.data;
        },
        error: function (data) {
          errorInfo(_this, "网络连接不畅");
        },
      });
    },
    /**
     * 提交课程封面
     */
    submitUploadCoverImage() {
      const _this = this;
      this.uploadCourseLoading = true;
      if (this.courseCoverImageFileList.length > 0) {
        this.src = URL.createObjectURL(this.courseCoverImageFileList[0].raw);
        const formData = new FormData();
        formData.append("file", this.courseCoverImageFileList[0].raw);
        formData.append(
          "fileName",
          _this.uploadCourseForm.courseName + new Date().getTime()
        );

        $.ajax({
          url: getHost() + "/fileCenter/file/uploadCourseCoverImage",
          data: formData,
          dataType: "json",
          type: "post",
          processData: false, // 告诉jQuery不要去处理发送的数据
          contentType: false, // 告诉jQuery不要去设置Content-Type请求头
          //加上这句话,允许浏览器向服务器跨域请求时携带cookie
          xhrFields: {
            withCredentials: true,
          },
          crossDomain: true,
          success: function (data) {
            _this.uploadCourseLoading = false;
            _this.coverImage = data.data;
            _this.$refs["upload"].clearFiles();
            successInfo(_this, data.message);
          },
          error: function (data) {
            _this.uploadCourseLoading = false;
            errorInfo(_this, "上传出错，请尝试改变文件大小之后再试");
          },
        });
      } else {
        warnInfo(_this, "您未选择任何文件");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.src = URL.createObjectURL(file.raw);
    },
    handleRemove(file, fileList) {
      if (fileList.length <= 0) {
        this.src = undefined;
      }
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChange(file, fileList) {
      this.courseCoverImageFileList = fileList;
      if (this.courseCoverImageFileList.length > 0) {
        this.src = URL.createObjectURL(this.courseCoverImageFileList[0].raw);
      } else {
        this.src = undefined;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../styles/common.css";
.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
